package ThreadDemo;

import java.util.Timer;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-27
 * Time: 18:42
 */
//线程池使用
public class ThreadPoolTest {

    public static void main(String[] args) {
        //使用线程池的工厂类创建一个固定数目的线程池
//        ExecutorService executor = Executors.newFixedThreadPool(4);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100000; i++) {
            int id = i;
            //添加任务
            executorService.submit(() -> {
                System.out.println("Runnable " + id + " " + Thread.currentThread().getName());
            },"Thread " + id + "");
        }
    }

    public static void main1(String[] args) {
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);
        //使用构造方法构造线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20,100,1000, TimeUnit.MICROSECONDS,workQueue);
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 1000; i++) {
            int id = i;
            //添加任务
            executor.submit(() -> {
                System.out.println("Runnable " + id + " " + Thread.currentThread().getName());
            },"Thread " + id + "");
        }
    }
}
